package com.yuke.cloud.service.smc.service.impl;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.DateUtil;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.omc.dto.OdsOrderApiDto;
import com.yuke.cloud.service.api.omc.dto.StoreOrderDto;
import com.yuke.cloud.service.api.omc.service.OmcOrderFeignApi;
import com.yuke.cloud.service.smc.dto.StoreShopDto;
import com.yuke.cloud.service.api.smc.service.SmcFeignApi;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.smc.dao.DmsStoreMapper;
import com.yuke.cloud.service.smc.dao.DmsVisitMapper;
import com.yuke.cloud.service.smc.dao.ShopMapper;
import com.yuke.cloud.service.smc.dto.DmsStoreDto;
import com.yuke.cloud.service.smc.dto.DmsVisitDto;
import com.yuke.cloud.service.smc.dto.SaleRankDto;
import com.yuke.cloud.service.smc.entity.DmsStore;
import com.yuke.cloud.service.smc.entity.DmsVisit;
import com.yuke.cloud.service.smc.entity.Shop;
import com.yuke.cloud.service.smc.service.DmsStoreService;
import com.yuke.cloud.service.smc.service.DmsVisitService;
import com.yuke.cloud.service.smc.service.ShopService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * Created by zn on 2020/07/16.
 */
@Service
@Transactional
public class DmsVisitServiceImpl extends BaseService<DmsVisit> implements DmsVisitService {
    @Resource
    private DmsVisitMapper dmsVisitMapper;
    @Resource
    private DmsStoreMapper dmsStoreMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private OmcOrderFeignApi omcOrderFeignApi;
    @Resource
    private DmsStoreService dmsStoreService;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Resource
    private SmcFeignApi smcFeignApi;
    @Resource
    private ShopService shopService;


    @Override
    public List<DmsVisitDto> selectVisitByCondition(DmsVisitDto dmsVisitDto) {
        List<DmsVisitDto> list = dmsVisitMapper.selectVisitByCondition(dmsVisitDto);
        return list;
    }

    @Override
    public List<DmsVisitDto> countVisit(DmsVisitDto dmsVisitDto) {
        //VisitStatus不为空,查询店铺去重,查到的为签约店铺
        if (dmsVisitDto.getVisitStatus()!=null){
            //byte a = 1;
            //dmsVisitDto.setVisitStatus(a);
            List<DmsVisitDto> list = dmsVisitMapper.countVisit(dmsVisitDto);
            return list;
        }
        //VisitStatus为空,即查询本月打卡信息,storeId不去重
        List<DmsVisitDto> list = dmsVisitMapper.countVisits(dmsVisitDto);
        return list;
    }

    //计算合作店铺
    @Override
    public PageInfo<OdsOrderApiDto> getAmountById(Long userId, Integer page, Integer size) {

        //根据store表:拿service_user_id=#{userId}或者其他条件查到相应的shopId及相关信息
        PageHelper.startPage(page, size);
        //查询到服务的店铺
        List<OdsOrderApiDto> list = dmsVisitMapper.findSocShopId(userId);

        PageInfo<OdsOrderApiDto> pageInfo = new PageInfo(list);

        List<Long> shopIdList = list.stream().map(OdsOrderApiDto::getShopId).collect(Collectors.toList());

        //本月时间在omcOrderFeignApi,根据shopId查询金额和下单次数

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String beginTime = formatter.format(DateUtil.monthTimeBegin());

        String endTime = formatter.format(DateUtil.monthTimeEnd());

        if (list != null && list.size() > 0  ) {
            List<OdsOrderApiDto> odsOrderApiDtoList = omcOrderFeignApi.countByShopIds(shopIdList, beginTime, endTime);
            if (odsOrderApiDtoList!=null) {
                for (OdsOrderApiDto orderApiDto : list) {
                  for (OdsOrderApiDto odsOrderApiDto : odsOrderApiDtoList) {
                        if (odsOrderApiDto.getShopId().equals(orderApiDto.getShopId())) {
                            orderApiDto.setAmountPayable( odsOrderApiDto.getAmountPayable());
                            orderApiDto.setOrderCount(odsOrderApiDto.getOrderCount());
                        }
                    }
                }
            }
            pageInfo.setList(list);
        }

        return pageInfo;
    }

    //查询visit中的storeId是否有shopId
    @Override
    public void checkShopId(Long storeId){

        //查询dms_store中的shopId
        //1.根据storeId查询dms_store中storeId,telephone,shopId等

        //DmsVisitDto visitDto = dmsVisitMapper.checkShopId(storeId);改用通用mapper

        DmsStore dmsStore = dmsStoreMapper.selectByPrimaryKey(storeId);

        //如果dms_store中的shopId为空
        if (dmsStore.getShopId()==null||dmsStore.getTelephone()!=null){
           /* 改用通用mapper
            DmsVisitDto dmsVisitDto=dmsVisitMapper.findShopIdByTelephone(dmsStore.getTelephone());*/

           //则根据手机号在shop表中查shopId
          Example example = new Example(Shop.class);
          Example.Criteria criteria = example.createCriteria();
          criteria.andEqualTo("telephone", dmsStore.getTelephone());
          List<Shop> shops = shopMapper.selectByExample(example);

          //如果shopId等于1,即只有一个值;
          //一个storeId对应一个shopId
            if (shops.size()==1){
                Shop shop = shops.get(0);
                //即存入store中
                dmsStore.setShopId(shop.getShopId());
                dmsStoreMapper.updateByPrimaryKey(dmsStore);
                System.out.println(dmsStore);
            }else{
                //处理
                System.out.println("未找到shopId");
            }
        }else{
            System.out.println(dmsStore.getShopId()+"已存在");
        }

    }



    @Override
    public List<DmsStoreDto> needDevStore(Long userId) {
        List<DmsStoreDto> list = dmsVisitMapper.needDevStore(userId);
        return list;
    }

    //本月已打卡的店铺 不去重
    @Override
    public List<DmsVisitDto> visitedStore(Long userId) {

        //本月
        Date beginTime = DateUtil.monthTimeBegin();

        Date endTime = DateUtil.monthTimeEnd();

        //返回打卡信息 店铺信息
        List<DmsVisitDto> storeList = dmsVisitMapper.findStoreIdListByUserId(userId,beginTime,endTime);

        System.out.println("storeList"+storeList.size());

        return storeList;
    }

    //所有已走访的店铺 去重
    @Override
    public List<DmsStoreDto> visitedAllStore(Long userId) {

        List<DmsStoreDto> storeList = dmsStoreMapper.findAllStoreByUserId(userId);

        return storeList;
    }


    @Override
    public List<DmsStoreDto> needVisitShop(Long userId, int num) {
      Calendar ca = Calendar.getInstance();
      // num为天数，可以改变的
      ca.add(Calendar.DATE, -num);
      Date endDate = ca.getTime();
      //System.out.println("更改天数以后的日期：" + enddate);
      //已打过卡的店铺最后一次打卡时间不在七天内
      List<DmsStoreDto> list=dmsStoreMapper.needVisitStore(userId,endDate);
      return list;
    }

    @Override
    public List<DmsStoreDto> visitInactiveStore(Long userId) {
        //下单较少的店铺
        List<DmsStoreDto> list = dmsStoreMapper.needVisitDescStore(userId);
        return list;
    }

    @Override
    public Map<String, Integer> userCount(Long userId) {

        HashMap<String, Integer> map = new HashMap<>();

        //本月已打卡店铺
        List<DmsVisitDto> list = visitedStore(userId);

        int visitedByMonth = list.size();

        map.put("visitedByMonth",visitedByMonth);

        //本月签约店铺数
        List<DmsStoreDto> partnersStoreByMonth = dmsStoreService.partnersStore(userId);

        int partnersByMonth = partnersStoreByMonth.size();

        map.put("partnersByMonth",partnersByMonth);


        //业务员总合作店铺数

        List<OdsOrderApiDto> socShopId = dmsVisitMapper.findSocShopId(userId);

        int allSocShopId = socShopId.size();

        map.put("allSocShopId",allSocShopId);

        return map;
    }

    @Override
    public List<DmsVisitDto> visitedStoreByDay(Long userId) {

        Long aLong = DateUtil.dayTimeInMillis();

        //今日零点
        Date today = new Date(aLong);

        System.out.println("今日零点:"+today);

        List<DmsVisitDto> visitedByDay = dmsVisitMapper.findStoreIdListByUserId(userId, today, null);

        return visitedByDay;
    }

    //1.需要回访的店铺 2.需要跟进的店铺 3.已经走访的店铺
    @Override
    public Map<String, Integer> homeCount(Long userId) {

        HashMap<String, Integer> map = new HashMap<>();
        //1.需要回访的店铺
        List<DmsStoreDto> list2 = needVisitShop(userId,7);

        int size = list2.size();

        List<DmsStoreDto> list3 = visitInactiveStore(userId);

        int size1 = list3.size();

        int needVisitShop = size+size1;

        map.put("needVisitShop",needVisitShop);

        //2.需要跟进的店铺
        List<DmsStoreDto> list1 = needDevStore(userId);

        int needDevStore = list1.size();

        map.put("needDevStore",needDevStore);

        //3.已经走访的店铺
        List<DmsVisitDto> list = visitedStoreByDay(userId);

        int visitedStoreByDay = list.size();

        map.put("visitedStoreByDay",visitedStoreByDay);

        return map;
    }

    @Override
    public List<SaleRankDto> sellRanking() {

        List<SaleRankDto>  rankList = new ArrayList<>();

        //获取所有业务员id
        List<Long> userList = dmsVisitMapper.findAllUserId();


        for (Long userId : userList) {

            Long money = 0L;

            SaleRankDto saleRankDto = new SaleRankDto();

            saleRankDto.setUserId(userId);

            saleRankDto.setAmountMoney(0L);
            //业务员本月合作店铺的下单金额
            PageInfo<OdsOrderApiDto> amountById = getAmountById(userId,0,0);

            List<OdsOrderApiDto> odsOrderApiDtos = amountById.getList();
            //将所有店铺下单金额累计
            for (OdsOrderApiDto odsOrderApiDto : odsOrderApiDtos) {
                if (odsOrderApiDto!=null&&odsOrderApiDto.getAmountPayable()!=null) {
                    Long amountPayable = odsOrderApiDto.getAmountPayable();
                    money +=amountPayable;
                }
                saleRankDto.setAmountMoney(money);
            }

           rankList.add(saleRankDto);
        }
        //根据Id查找业务员姓名
        Wrapper<List<UserInfoDto>> userInfoByUserIds = uacUserFeignApi.getUserInfoByUserIds(userList);

        List<UserInfoDto> result = userInfoByUserIds.getResult();
        //将业务员姓名赋值给dto中
            for (UserInfoDto userInfoDto : result) {
                for (SaleRankDto saleRankDto : rankList) {
                 if (saleRankDto.getUserId().equals(userInfoDto.getUserId())){
                     saleRankDto.setUserName(userInfoDto.getUserName());
                }
            }
        }

        Collections.sort(rankList, new Comparator<SaleRankDto>() {
            @Override
            public int compare(SaleRankDto o1, SaleRankDto o2) {
                return (int) (o2.getAmountMoney() - o1.getAmountMoney());
            }
        });
        //设置排名
        for (int i = 0; i < rankList.size(); i++) {
            rankList.get(i).setRanking(i+1);
        }

        System.out.println("----------------------");
        for (SaleRankDto saleRankDto : rankList) {
            System.out.println(saleRankDto);
        }
        return rankList;
    }

    @Override
    public List<DmsStoreDto> needServiceShop() {

        List<DmsStoreDto> list = dmsStoreMapper.needServiceShop();

        return list;
    }

    @Override
    public List<DmsStoreDto> publicDevStore() {

        List<DmsStoreDto> list = dmsStoreMapper.publicDevStore();

        return list;
    }

    @Override
    public PageInfo<OdsOrderApiDto> countShopByStoreId(Long userId, Integer page, Integer size) {

        //根据store表:拿service_user_id=#{userId}或者其他条件查到相应的shopId及相关信息
        PageHelper.startPage(page, size);
        //查询到服务的店铺 shopId不为空的店铺
        List<OdsOrderApiDto> list = dmsVisitMapper.findSocShopId(userId);

        PageInfo<OdsOrderApiDto> pageInfo = new PageInfo(list);

        System.out.println("11111111111");
        List<Long> storeIdList = list.stream().map(OdsOrderApiDto::getStoreId).collect(Collectors.toList());

        //每个storeId对应的shopID
        List<StoreShopDto> shopByStore = shopService.findShopByStore(storeIdList);

        //本月时间在omcOrderFeignApi,根据shopId查询金额和下单次数
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String beginTime = formatter.format(DateUtil.monthTimeBegin());
        System.out.println("日期"+beginTime);

        String endTime = formatter.format(DateUtil.monthTimeEnd());



        //for (StoreShopDto dto : shopDtoList) {
        //    for (Long shopId : dto.getShopList()) {
        //        List<Long> shopList = new ArrayList<>();
        //        new
        //        shopList.add(shopId);
        //        map.put(dto.getStoreId(),shopList);
        //    }
        //}
        List<StoreOrderDto> storeOrderDtos = new ArrayList<>();

        System.out.println("2222222");

        for (StoreShopDto storeShopDto : shopByStore) {
            if (storeShopDto != null) {
                StoreOrderDto storeOrderDto = new StoreOrderDto();
                BeanUtils.copyProperties(storeShopDto, storeOrderDto);
                storeOrderDtos.add(storeOrderDto);
            }
        }

        System.out.println("111111111111");


        //OdsOrderDto orderAndGoodsByOrderId = omcOrderFeignApi.getOrderAndGoodsByOrderId(241690759580221440L);

        //String json = JSON.toJSONString(storeOrderDtos);
        List<StoreOrderDto>  countList = omcOrderFeignApi.countByShopListByStoreOrderDtos(storeOrderDtos);




        return pageInfo;
    }


}
